package com.zyg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyg.dao.UserMapper;
import com.zyg.pojo.User;
import com.zyg.pojo.UserRole;
import com.zyg.service.UserRoleService;
import com.zyg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("userService")
public class  UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleService userRoleService;


    @Override
    public List<User> findAll(User user, int offset, int pageSize) {

        return userMapper.findAll(user,offset,pageSize);
    }

    @Override
    @Transactional
    public int addUser(User user) {
        int result = userMapper.addUser(user);
        //获取新增用户的主键
        int userId = user.getId();
        //遍历处理角色数据
        Long[] roleIds = user.getRoleIds();
        //构造userRole集合
        for(Long roleId:roleIds){
            UserRole userRole =  new UserRole();
            userRole.setUId(userId);
            userRole.setRId(roleId.intValue());
            userRoleService.save (userRole);
        }
        return result;
    }

    @Override
    public int deleteUser(Integer id) {
        return userMapper.deleteUser (id);
    }

    @Override
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }

    @Override
    @Transactional
    public int updateUser(User user) {
       int result =  userMapper.updateUser(user);
               //user_role 数据更新
        //先删除此用户相关角色
        QueryWrapper qw = new QueryWrapper();
       qw.eq("u_id",user.getId());
        userRoleService.remove(qw);
        //再插入传递过来的用户角色数据
        //遍历处理角色数据
        Long[] roleIds = user.getRoleIds();
        //构造userRole集合
        for(Long roleId:roleIds){
            UserRole userRole = new UserRole();
            userRole.setUId(user.getId());
            userRole.setRId (roleId.intValue());
            userRoleService.save(userRole);
        }
        return result;
    }

    @Override
    public int count(User user) {
        return userMapper.count(user);
    }

    @Override
    public User login(User user) {
        return userMapper.login(user);

    }

    @Override
    public User findUserByUserName (String username) {
        User user = userMapper.findUserByUserName(username);
        return user;
    }
}















